import axios from 'axios'

const BASE_URL = 'http://localhost:3000'

// 用户相关
export const getCurrentUser = () => {
  // 从 localStorage 获取当前用户信息
  const userId = localStorage.getItem('userId')
  if (!userId) {
    return Promise.reject(new Error('未登录'))
  }
  return axios.get(`${BASE_URL}/users/${userId}`)
}

export const login = (username, password) => {
  return axios.post(`${BASE_URL}/login`, { username, password })
}

// 医生相关
export const getDoctors = () => {
  return axios.get(`${BASE_URL}/doctors`)
}

export const getDoctorPatients = (doctorId) => {
  // 从 consultations 表中获取与该医生有对话的患者
  return axios.get(`${BASE_URL}/consultations`, {
    params: { doctorId }
  }).then(response => {
    // 获取所有不重复的患者ID
    const patientIds = [...new Set(response.data.map(c => c.patientId))]
    // 获取这些患者的详细信息
    return Promise.all(patientIds.map(id => 
      axios.get(`${BASE_URL}/users/${id}`)
    )).then(patients => ({
      data: patients.map(p => p.data)
    }))
  })
}

export const updateDoctorStatus = (doctorId, status) => {
  return axios.patch(`${BASE_URL}/doctors/${doctorId}`, { status })
}

// 咨询相关
export const getConsultations = (params) => {
  return axios.get(`${BASE_URL}/consultations`, { params })
}

export const sendMessage = (data) => {
  // 查找是否已存在该医生和患者的对话
  return axios.get(`${BASE_URL}/consultations`, {
    params: {
      doctorId: data.doctorId,
      patientId: data.patientId
    }
  }).then(response => {
    const existingConsultation = response.data[0]
    const message = {
      id: `msg${Date.now()}`,
      content: data.content,
      sender: data.sender,
      time: new Date().toISOString()
    }

    if (existingConsultation) {
      // 更新现有对话
      return axios.patch(`${BASE_URL}/consultations/${existingConsultation.id}`, {
        messages: [...existingConsultation.messages, message],
        lastMessageTime: message.time
      }).then(() => ({ data: message }))
    } else {
      // 创建新对话
      return axios.post(`${BASE_URL}/consultations`, {
        doctorId: data.doctorId,
        patientId: data.patientId,
        messages: [message],
        status: 'active',
        createTime: message.time,
        lastMessageTime: message.time
      }).then(() => ({ data: message }))
    }
  })
}

// 获取医生信息
export const getDoctorInfo = (doctorId) => {
  return axios.get(`${BASE_URL}/doctors/${doctorId}`)
}

// 获取患者信息
export const getPatientInfo = (patientId) => {
  return axios.get(`${BASE_URL}/users/${patientId}`)
}

// 获取所有用户信息（用于管理员查看）
export const getUsers = () => {
  return axios.get(`${BASE_URL}/users`)
}

// 更新咨询状态
export const updateConsultationStatus = (consultationId, status) => {
  return axios.patch(`${BASE_URL}/consultations/${consultationId}`, { status })
}

// 删除咨询
export const deleteConsultation = (consultationId) => {
  return axios.delete(`${BASE_URL}/consultations/${consultationId}`)
} 